#!/usr/bin/env python3
# coding: utf-8
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# This file is a part of the CANN Open Software.
# Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# ======================================================================================================================
import random
import torch
import math 
import copy
from typing import Union, List

from atk.case_generator.generator.generate_types import GENERATOR_REGISTRY
from atk.case_generator.generator.base_generator import CaseGenerator
from atk.configs.case_config import InputCaseConfig, CaseConfig

def get_random_factor_divisible_by_2(K):
    if K <= 0:
        raise ValueError("K 必须是正整数")
    
    # 找出所有正整数因子
    factors = set()
    for i in range(1, int(math.sqrt(K)) + 1):
        if K % i == 0:
            factors.add(i)
            factors.add(K // i)
    
    # 约束6：每个切分后的K必须为偶数
    divisible_by_2 = [f for f in factors if f % 2 == 0]
    
    if not divisible_by_2:
        raise ValueError(f"{K}没有能被2整除的因子")
    
    # 随机选择一个能被8整除的因子
    return random.choice(divisible_by_2)

@GENERATOR_REGISTRY.register("ascend_generate_grouped_matmul_V4_a4w4")
class AscendGroupedMatmulV4A8W4(CaseGenerator):
    def __init__(self, config):
        super().__init__(config)

    def after_input_config(
            self,
            index: int,
            input_case: Union[InputCaseConfig, List[InputCaseConfig]]
    ) -> Union[InputCaseConfig, List[InputCaseConfig]]:

        return input_case

    def after_case_config(self, case_config: CaseConfig) -> CaseConfig:
        x = case_config.inputs[0]
        weight = case_config.inputs[1]
        scaleOptional = case_config.inputs[2]
        perTokenScaleOptional = case_config.inputs[3]
        groupListOptional = case_config.inputs[4]
        groupListType = case_config.inputs[7]
        weightFormat = case_config.inputs[9]
        E = weight[0].shape[0] 
        # 约束0 : E <= 1024;
        if E > 1024:
            E = 1024
        M = x[0].shape[0]
        K = x[0].shape[1]
        N = weight[0].shape[2]
        if weightFormat.range_values == 1: # NZ场景
            # 约束1 : K < 65536 N < 65536;
            K = K if K < 65536 else 65472
            N = N if N < 65536 else 65472
            # 约束2 : weight NZ场景， K 需要16对齐，N需要64对齐;
            K = (K if K % 16 == 0 else ((K + 15) // 16 * 16))
            N = (N if N % 64 == 0 else ((N + 63) // 64 * 64))
        elif weightFormat.range_values == 0: # ND场景
            # 约束1 : K < 65536 N < 65536;
            K = K if K < 65536 else 65472
            N = N if N < 65536 else 65472
            # 约束3 : weight ND 场景， K 需要8对齐，N需要8对齐; 
            K = (K if K % 8 == 0 else ((K + 7) // 8 * 8))
            N = (N if N % 8 == 0 else ((N + 7) // 8 * 8))
        x[0].shape = M, K
        # 约束4 : int4 的有效数据范围 -8，7
        x[0].range_values = [-8, 7]
        weight[0].shape = E, K, N
        weight[0].range_values = [-8, 7]
        # 随机选择一个可被K整除的正整数作为quantGroupSize
        # 约束5 : K可被quantGroupSize整除
        quantGroupSize = get_random_factor_divisible_by_2(K)
        if len(scaleOptional[0].shape) == 3:
            scaleOptional[0].shape[0], scaleOptional[0].shape[1], scaleOptional[0].shape[2] = E, int(K // quantGroupSize), N 
        if len(scaleOptional[0].shape) == 2:
            scaleOptional[0].shape[0], scaleOptional[0].shape[1] = E, N
        perTokenScaleOptional[0].shape[0] = M
        groupListOptional.shape[0] = E
        groupListType.range_values=[0,1]
        return case_config
